package com.woniuxy.service.impl;

import com.woniuxy.entity.MUser;
import com.woniuxy.entity.MUserExample;
import com.woniuxy.mapper.MUserMapper;
import com.woniuxy.service.UserService;
import com.woniuxy.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    MUserMapper mapper;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public MUser login(String userName, String passWord) {
        MUserExample mUserExample = new MUserExample();
        mUserExample.or().andPasswordEqualTo(passWord).andUsernameEqualTo(userName);
        List<MUser> mUsers = mapper.selectByExample(mUserExample);
        if (mUsers.size() == 0) {
            throw new RuntimeException("登陆失败"+userName);
        }
        return mUsers.get(0);
    }

    @Override
    public MUser loginByEmailCode(String email, String code) {
        MUserExample mUserExample = new MUserExample();
        mUserExample.or().andEmailEqualTo(email);
        List<MUser> mUsers = mapper.selectByExample(mUserExample);
        String redisCode = redisTemplate.opsForValue().get(email).toString();
        if (mUsers.size() == 0 || !code.equals(redisCode)) {
            throw new RuntimeException("账户不存在或验证码错误");
        }
        return mUsers.get(0);
    }

    @Override
    public MUser getLoginUser(String token) {
        String loginId = JwtUtils.getLoginId(token);
        MUser mUser = mapper.selectByPrimaryKey(Long.valueOf(loginId));
        if (mUser == null) {
            throw new RuntimeException("用户不存在，头像查询失败");
        }
        return mUser;
    }

    @Override
    public List<MUser> getSomeUser(HashSet<Long> allFriends2) {
        List<Long> list = new ArrayList<>(allFriends2);
        System.out.println(list+"ID名单+++++++++++++++++++++++++++++++++++");

        MUserExample mUserExample = new MUserExample();
        mUserExample.or().andIdIn(list);

        List<MUser> mUsers = mapper.selectByExample(mUserExample);

        return mUsers;
    }
}
